<?php

namespace App\Admin\Forms\Posts;

use App\Http\Controllers\Api\Repositories\WxCommentRepositores;
use App\Jobs\CalculateCommentLikesNumJob;
use App\Jobs\ImitateCircleJoinStepJob;
use App\Jobs\SubscribeMessageJob;
use App\Models\Posts\WxComment;
use App\Models\Posts\WxPost;
use App\Wen\Utils\Settings;
use App\Wen\Utils\UserUtils;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class CommentReplayForm extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * 处理表单请求.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        global $__MINI_GLOBAL_IS_ADMIN_SUPER__;
        if(!$__MINI_GLOBAL_IS_ADMIN_SUPER__){
            return $this->response()
                ->error('仅允许超级管理员模拟回复.');
        }
        $comment_id = $input['id'];
        $who = $input['who'];
        $content = $input['content'];
        $img_url = $input['img_url'];

        if(_empty_($comment_id) || _empty_($who) || _empty_($content)){
            return $this->response()
                ->error('参数错误.');
        }

        $comment = WxComment::find($comment_id);
        if(!$comment){
            return $this->response()
                ->error('评论不存在.');
        }

        $uid = $comment->posts_user_id;
        if($who == 2){
            $uid = $comment->comment_agent_id;
        }

        $parent_comment_id = 0;
        $reply_user_id = 0;
        if(_empty_($comment->comment_id)){
            $parent_comment_id = $comment->id;
            $reply_user_id = $comment->user_id;
        }else{
            $parent_comment_id = $comment->comment_id;
            $reply_user_id = $comment->user_id;
        }

        if(strpos($img_url, 'http') !== 0){
            $img_url = '';
        }

        DB::beginTransaction();
        try {
            // todo:
            $r = WxCommentRepositores::add($comment->posts_id, $parent_comment_id, $reply_user_id, $uid,  $content, $img_url, 1, '');
            if($r){
                Redis::sadd('realtime:post:set', $comment->posts_id);
                Cache::put('user:comment:cahce:'.$uid, 1, 10);
                CalculateCommentLikesNumJob::dispatch($r);
                if($parent_comment_id && $parent_comment_id > 0){
                    CalculateCommentLikesNumJob::dispatch($parent_comment_id);
                }

                $circle_id = WxPost::where('id', $comment->posts_id)->value('circle_id');
                if($circle_id && $circle_id > 0){
                    ImitateCircleJoinStepJob::dispatch($circle_id, mini_rand(1, 100) <= 30 ? mini_rand(1, 2) : 0)->delay(now()->addMinutes(mini_rand(1, 20)));
                }

                SubscribeMessageJob::dispatch('comment_add', $r);
                if($parent_comment_id > 0){
                    SubscribeMessageJob::dispatch('comment_reply', $r);
                }
                $msg = UserUtils::reward_user_coin($uid, 'comment');
                DB::commit();
                return $this->response()
                    ->success('回复成功.')
                    ->refresh();
            }
        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return $this->response()
                ->error('出现错误，已记录到日志.');
        }
    }

    /**
     * 构建表单.
     */
    public function form()
    {
        $comment_id = $this->payload["id"];
        if($comment_id && $comment_id > 0){
            $comment = WxComment::find($comment_id);
            if($comment){
                $post_author = UserUtils::get_cached_user($comment->posts_user_id);
                $options = [
                    1 => '笔记作者：'.$post_author['user_name']
                ];

                if($comment->comment_agent_id && $comment->comment_agent_id > 0){
                    $agent_user = UserUtils::get_cached_user($comment->comment_agent_id);
                    $options[2] = '被回复者：'.$agent_user['user_name'];
                }

                $this->hidden('id')->value($comment_id);
                $this->radio('who', '以谁的身份')->options($options)->default(1)->required();
                $this->textarea('content', '回复内容')->required();
                $this->image('img_url', '图片')->url('files/uploads')->autoUpload();
            }
        }
    }

}
